package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.VisitorMessageAdapter;
import com.wnhz.work.yz.bean.ApplyMessagebean;
import com.wnhz.work.yz.bean.VisitdistrictBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * -------来访情况
 */
public class VisitorMessage extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "VisitorMessage";

    private TextView tv_visitor_house;
    private TextView tv_visitor_eat;
    private ListView nsLv_visitor;
    private ScrollView sc_visitor;

    private VisitorMessageAdapter visitorMessageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_visitor_message);
        getFangWen();

    }

    private List<VisitdistrictBean.InfoEntity> info1 = new ArrayList<>();

    private void getFangWen() {
        Map<String, Object> map = new HashMap<>();
        showDialog();
        XUtil.Post(Url.INFORMATION_VISITDISTRICT, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        VisitdistrictBean bean = gson.fromJson(result, VisitdistrictBean.class);
                        info1 = bean.getInfo();

                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                initData();
                initTitle();
                initView();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });
    }

    private List<ApplyMessagebean.VisitInfoEntity.VisitDistrictInfoEntity> visit_district_info = new ArrayList<>();
    private ApplyMessagebean.VisitInfoEntity.FoodInfoEntity food_info = new ApplyMessagebean.VisitInfoEntity.FoodInfoEntity();
    private ApplyMessagebean.VisitInfoEntity.HotelInfoEntity hotel_info = new ApplyMessagebean.VisitInfoEntity.HotelInfoEntity();

    private void initData() {
        food_info = ApplyMessageActivity.bean.getVisit_info().getFood_info();
        hotel_info = ApplyMessageActivity.bean.getVisit_info().getHotel_info();

        visit_district_info =
                ApplyMessageActivity.bean.getVisit_info().getVisit_district_info();

//        for (int i = 0; i < info1.size(); i++) {
//            ApplyMessagebean.VisitInfoEntity.VisitDistrictInfoEntity dis = new ApplyMessagebean.VisitInfoEntity.VisitDistrictInfoEntity();
//            dis.setDistrict_id(info1.get(i).getId());
//            dis.setStarttime("开始时间");
//            dis.setEndtime("结束时间");
//            dis.setShow(false);
//            dis.setVisit_district(info1.get(i).getVisit_district());
//            visit_district_info.add(dis);
//        }
        String a[] = new String[visit_district_info.size()];
        for (int i = 0; i < visit_district_info.size(); i++) {
            a[i] = visit_district_info.get(i).getDistrict_id();
        }
        String b[] = new String[info1.size()];
        for (int i = 0; i < info1.size(); i++) {
            b[i] = info1.get(i).getId();
        }

        String[] c = minus(a, b);
        for (int i = 0; i < info1.size(); i++) {
            for (int j = 0; j < c.length; j++) {
                if (info1.get(i).getId().equals(c[j])) {
                    ApplyMessagebean.VisitInfoEntity.VisitDistrictInfoEntity dis = new ApplyMessagebean.VisitInfoEntity.VisitDistrictInfoEntity();
                    dis.setDistrict_id(info1.get(i).getId());
                    dis.setStarttime("开始时间");
                    dis.setEndtime("结束时间");
                    dis.setShow(false);
                    dis.setVisit_district(info1.get(i).getVisit_district());
                    visit_district_info.add(dis);

                }


            }
        }


    }

    public String[] minus(String[] arr1, String[] arr2) {
        LinkedList list = new LinkedList();
        LinkedList history = new LinkedList();
        String[] longerArr = arr1;
        String[] shorterArr = arr2;
        //找出较长的数组来减较短的数组
        if (arr1.length > arr2.length) {
            longerArr = arr2;
            shorterArr = arr1;
        }
        for (String str : longerArr) {
            if (!list.contains(str)) {
                list.add(str);
            }
        }
        for (String str : shorterArr) {
            if (list.contains(str)) {
                history.add(str);
                list.remove(str);
            } else {
                if (!history.contains(str)) {
                    list.add(str);
                }
            }
        }

        String[] result = {};
        return (String[]) list.toArray(result);
    }


    private TextView title;

    private void initTitle() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("来访情况");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView tv_right = (TextView) findViewById(R.id.submit);
        tv_right.setText("保存");
        tv_right.setTextColor(Color.parseColor("#008c99"));
        tv_right.setVisibility(View.VISIBLE);
        findViewById(R.id.submit).setVisibility(View.VISIBLE);
        findViewById(R.id.submit).setOnClickListener(this);
    }

    private void initView() {
        sc_visitor = (ScrollView) findViewById(R.id.sc_visitor);

        tv_visitor_house = (TextView) findViewById(R.id.tv_visitor_house);
        tv_visitor_eat = (TextView) findViewById(R.id.tv_visitor_eat);

        nsLv_visitor = (ListView) findViewById(R.id.nsLv_visitor);

        visitorMessageAdapter = new VisitorMessageAdapter(this, visit_district_info, this);
        nsLv_visitor.setAdapter(visitorMessageAdapter);

        if ("1".equals(food_info.getIs_food())) {
            tv_visitor_eat.setText(food_info.getFood_level());
        }
        if (!"".equals(hotel_info.getHotel_level())) {
            hotel_info.setIs_hotel("1");
            tv_visitor_house.setText(hotel_info.getHotel_level());
        }

        if (ApplyMessageActivity.bean.getCanUpdata().equals("0")) {


        } else {
            findViewById(R.id.rl_visitor_house).setOnClickListener(this);
            findViewById(R.id.rl_visitor_eat).setOnClickListener(this);

        }
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {

            case R.id.btn_main_left:
                finish();
                break;

            //保存
            case R.id.submit:
//                MyToast("保存");
                int num = 0;
                int numS = 0;
                for (int i = 0; i < info1.size(); i++) {
                    Log.e("---", visit_district_info.get(i).isShow() + "");
                    if (visit_district_info.get(i).getStarttime().equals("开始时间") || visit_district_info.get(i).getEndtime().equals("结束时间")) {
                        num++;
                        visit_district_info.get(i).setShow(false);
                    }
                    if (!visit_district_info.get(i).isShow()) {
                        numS++;
                    }
                }
                // Log.e("" + num, numS + "==" + info1.size());
                if (num != 0 && num == info1.size() || numS == info1.size()) {
                    MyToast("至少选择一个展馆");
                    return;
                }
                setResult(RESULT_OK);
                finish();
                break;

            //switchButton按钮
            case R.id.sw_showVisitTimes:
                int index = (Integer) v.getTag();
                visit_district_info.get(index).setShow(!visit_district_info.get(index).isShow());
                visitorMessageAdapter.notifyDataSetChanged();

                break;

            //住宿要求
            case R.id.rl_visitor_house:
                intent = new Intent(this, StayHouseActivity.class);
                startActivityForResult(intent, IS1);
                break;

            //用餐要求
            case R.id.rl_visitor_eat:
                intent = new Intent(this, EatStandardActivity.class);
                startActivityForResult(intent, IS2);
                break;

            //开始时间
            case R.id.tv_item_startTime: {
                final int indexStart = (Integer) v.getTag();
                showDateDialog((TextView) v, indexStart, true);
            }
            break;


            //结束时间
            case R.id.tv_item_endTime: {
                final int indexStart = (Integer) v.getTag();
                showDateDialog((TextView) v, indexStart, false);
            }
            break;
            default:
                break;
        }
    }

    public static final int IS1 = 1;
    public static final int IS2 = 321;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IS1:
                    tv_visitor_house.setText(ApplyMessageActivity.bean.getVisit_info().getHotel_info().getHotel_level());

                    break;
                case IS2:
                    tv_visitor_eat.setText(ApplyMessageActivity.bean.getVisit_info().getFood_info().getFood_class() + "");
                    break;
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void showDateDialog(final TextView te, final int indexStart, final boolean flag) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        String[] b = str.split("-");
        Calendar startDate = Calendar.getInstance();
        startDate.set(Integer.parseInt(b[0]), Integer.parseInt(b[1]) - 1, Integer.parseInt(b[2]));
        Calendar endDate = Calendar.getInstance();
        endDate.set(2110, 10, 29);
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String defaultTime = format.format(date);
                if (flag) {
                    visit_district_info.get(indexStart).setStarttime(defaultTime);
                } else {
                    visit_district_info.get(indexStart).setEndtime(defaultTime);
                }

                te.setText(defaultTime);
                visitorMessageAdapter.notifyDataSetChanged();
            }
        })
                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色
                .setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)//默认全部显示
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .setTitleBgColor(getResources().getColor(R.color.white))//标题背景颜色 Night mode
                .setBgColor(getResources().getColor(R.color.white))//滚轮背景颜色 Night mode
                .setRangDate(startDate, endDate)//默认是1960-2110年
                .setDate(startDate)// 默认是系统时间*/
                .build();
        pvTime.show();
    }
}
